package com.keya.features.job;

import com.keya.device.GatewayProperties;
import com.keya.pacs.PacsService;
import com.keya.pull.DatasourcePacsVO;
import com.keya.pull.PublicParamKey;
import com.keya.pull.PublicParamService;
import com.keya.pull.PullStudyRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Configuration
@EnableScheduling
@Slf4j
public class FindStudyFromPACSJob implements ScheduledOfTask {

    @Resource
    private PullStudyRecordService pullStudyRecordService;
    @Resource
    private PublicParamService publicParamService;
    @Resource
    private GatewayProperties gatewayProperties;
    @Resource
    PacsService pacsService;

    @Override
    public String getCron() {
        return "0 */1 * * * *";
    }

    @Override
    public boolean isEnabled() {
        DatasourcePacsVO config = publicParamService.getDatasourcePacs();
        return config != null && Boolean.TRUE.equals(config.getEnabled());
    }

    @Override
    public void execute() {
        try {
            List<Integer> configDeviceIds = Optional.ofNullable(publicParamService.getDatasourcePacs())
                    .map(DatasourcePacsVO::getDeviceIds).orElse(Collections.emptyList());
            if (configDeviceIds.size() == 0) {
                log.error("{} DeviceIds未配置 SyncStudiesFromDBJob", PublicParamKey.DATA_SOURCE_PACS);
                return;
            }
            for (Integer deviceId : configDeviceIds) {
                try {
                    pullStudyRecordService.saveBatch(pacsService.list(deviceId, gatewayProperties.isPullFilterByStudyDate()));
                } catch (Exception e) {
                    log.error("FindStudyFromPACSJob 失败", e);
                }
            }
        } catch (Exception e) {
            log.error("FindStudyFromPACSJob 失败", e);
        }
    }

}
